<template>
  <div class="login">
    <div class="login-box">
      <div class="login-introduce">
        <div class="introduce-title">
          <img class="logo" src="@/assets/logo/logo.png" />
          <h3 class="title">{{ title }}</h3>
        </div>
        <div class="introduce-tip">
          <img class="tip-img" src="@/assets/images/login-intro.png" />
          <span class="tip-text">助力公司提升运营效率与决策能力</span>
        </div>
      </div>
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="title">登录</h3>
        <template v-if="userBox">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号">
              <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password"  show-password size="large" auto-complete="off" placeholder="密码" @keyup.enter="handleLogin">
              <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter="handleLogin">
              <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" />
            </div>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item prop="phone">
            <el-input v-model="loginForm.phone" type="text" size="large" auto-complete="off" placeholder="手机号码">
              <template #prefix><svg-icon icon-class="phone" class="el-input__icon input-icon" /></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captchaCode">
            <el-input  v-model="loginForm.captchaCode" size="large" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter="handleLogin">
              <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
            </el-input>
            <div class="code-btn">
              <el-button type="primary" @click="getSmsCode">{{codeTime <= 0 ? '获取验证码' : codeTime + 's后失效'}}</el-button>
            </div>
          </el-form-item>
        </template>
        <el-form-item>
          <div class="login-other">
            <el-checkbox v-model="loginForm.rememberMe">{{ userBox? '记住密码' : '记住手机号' }}</el-checkbox>
            <el-button link type="primary" v-if="smsCaptcha" @click="switchLogin">{{ userBox? '短信验证登录' : '用户名密码登录' }}</el-button>
          </div>
        </el-form-item>
        <el-form-item style="width:100%;">
          <el-button :loading="loading" size="large" type="primary" style="width:100%;" @click.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup>
import { getCodeImg, getAuthCode } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from "@/utils/jsencrypt"
import useUserStore from '@/store/modules/user'

const title = import.meta.env.VITE_APP_TITLE
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const loginForm = ref({
  username: "",
  password: "",
  phone: "",
  captchaCode: "",
  rememberMe: false,
  code: "",
  uuid: ""
})

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  phone: [
    { required: true, trigger: "blur", message: "请输入您的手机号" },
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  captchaCode: [{ required: true, trigger: "blur", message: "请输入验证码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
}

const codeUrl = ref("")
const loading = ref(false)
// 验证码开关
const captchaEnabled = ref(false)
// 注册开关
const register = ref(false)
// 短信验证开关
const smsCaptcha = ref(true)
const userBox = ref(true)
let timeInterval = null
const codeTime = ref(0)
const redirect = ref(undefined)

watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect
}, { immediate: true })

function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true
      let userInfo = {}
      if(userBox.value) {
        // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
        if (loginForm.value.rememberMe) {
          Cookies.set("username", loginForm.value.username, { expires: 30 })
          Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 })
          Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 })
        } else {
          // 否则移除
          Cookies.remove("username")
          Cookies.remove("password")
          Cookies.remove("rememberMe")
        }
        userInfo = {
          password: {username: loginForm.value.username.trim(), password: loginForm.value.password, code: loginForm.value.code, uuid: loginForm.value.uuid}
        }
      } else {
        // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
        if (loginForm.value.rememberMe) {
          Cookies.set("phone", loginForm.value.phone, { expires: 30 })
        } else {
          // 否则移除
          Cookies.remove("phone")
        }
        userInfo = {
          captcha: {phone: loginForm.value.phone.trim(), captchaCode: loginForm.value.captchaCode}
        }
      }
      // 调用action的登录方法
      userStore.login(userInfo).then(() => {
        const query = route.query
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
        router.push({ path: redirect.value || "/", query: otherQueryParams })
      }).catch(() => {
        loading.value = false
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode()
        }
      })
    }
  })
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img
      loginForm.value.uuid = res.uuid
    }
  })
}

function getCookie() {
  const username = Cookies.get("username")
  const password = Cookies.get("password")
  const rememberMe = Cookies.get("rememberMe")
  const phone = Cookies.get("phone")
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
    phone: phone === undefined ? loginForm.value.phone : phone
  }
}

function switchLogin() {
  userBox.value = !userBox.value
}

function getSmsCode() {
  if(codeTime.value > 0) return
  proxy.$refs.loginRef.validateField('phone', valid => {
    if (valid) {
      getAuthCode(loginForm.value.phone).then(res => {
        codeTime.value = 60
        timeInterval = setInterval(() => {
          codeTime.value -= 1
          if (codeTime.value <= 0) {
            clearTime()
          }
        }, 1000)
      })
    }
  })
}

function clearTime() {
  if(timeInterval) {
    clearInterval(timeInterval)
    timeInterval = null
  }
}

onBeforeUnmount(() => {
  clearTime()
})

// getCode()
getCookie()
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  position: relative;
  background-color: var(--el-bg-color-overlay);
  &::before  {
    content: '';
    position: absolute;
    left: 0;
    bottom: 0;
    width: 394px;
    height: 468px;
    background: url('../assets/images/login-left.png') no-repeat;
    background-size: cover;
  }
  &::after {
    content: '';
    position: absolute;
    right: 0;
    bottom: 0;
    width: 487px;
    height: 412px;
    background: url('../assets/images/login-right.png') no-repeat;
    background-size: cover;
  }
  .login-box{
    display: flex;
    border-radius: 6px;
    background: var(--el-bg-color);
    z-index: 1;
    box-shadow: 0px 20px 80px 0px rgba(0, 0, 0, 0.3);
  }
}
.login-introduce{
  width: 400px;
  background-color: var(--el-color-info-light-9);
  padding: 25px;
  display: flex;
  flex-direction: column;
  .introduce-title{
    display: flex;
    align-items: center;
    gap: 20px;
    .logo{
      width: 40px;
      height: 40px;
    }
    .title{
      color: var(--el-text-color-primary);
    }
  }
  .introduce-tip{
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 25px;
    .tip-img{
      width: 160px;
      height: 160px;
      animation: float 3s linear 0s infinite;
    }
    .tip-text{
      font-size: var(--el-font-size-small);
      color: var(--el-text-color-regular);
    }
  }
}
.login-form {
  width: 400px;
  padding: 25px 25px 5px 25px;
  .title {
    margin-bottom: 30px;
    color: var(--navbar-text);
  }
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.code-btn{
  width: 37%;
  display: flex;
  justify-content: flex-end;
}
.login-other{
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  z-index: 1;
  width: 100%;
  text-align: center;
  color: var(--navbar-text);
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}
@keyframes float {
  0% {
    transform: translateY(0);
  }
  25% {
    transform: translateY(-20px);
  }
  50% {
    transform: translateY(0px);
  }
  75% {
    transform: translateY(20px);
  }
  100% {
    transform: translateY(0);
  }
}
/* 移动端适配 */
@media (max-width: 800px) {
  .login-introduce {
    display: none !important;
  }
}
</style>
